<?php

declare(strict_types=1);
/**
 * Author: Zane
 * Email: 873934580@qq.com
 * Date: 2023/7/12.
 */

namespace App\Http\Controllers\System;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Traits\StoreTrait;
use App\Service\CategoryService;
use App\Utils\ResultsVo;

class CategoryController extends Controller
{
    use StoreTrait;

    protected $categoryService;

    public function __construct(CategoryService $categoryService)
    {
        parent::__construct();
        $this->categoryService = $categoryService;
    }

    public function tree(): \Illuminate\Http\JsonResponse
    {
        $data = $this->categoryService->getAll();
        $result = [];
        infiniteLevel($data, $result);

        $results[] = ['value' => 0, 'label' => '顶级栏目'];
        foreach ($result as $item) {
            if ($item['lv'] > 0) {
                $item['title'] = '|'.str_repeat('-', $item['lv']).$item['title'];
            }

            $results[] = [
                'value' => $item['id'],
                'label' => $item['title'],
            ];
        }

        return ResultsVo::success($results);
    }

    public function index(): \Illuminate\Http\JsonResponse
    {
        $data = $this->categoryService->getAll();

        return ResultsVo::success(['results' => infiniteTree($data)]);
    }
}
